package com.zhiwang.planet.ui


import androidx.fragment.app.Fragment
import com.zhiwang.planet.App
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.event.LogoutEvent
import com.zhiwang.planet.exception.ExpiredException
import com.zhiwang.planet.mvp.v.AuthView
import com.zhiwang.planet.util.ChannelUtil
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.TokenManager
import com.zhiwang.planet.util.quickStartActivity
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus

/**
 * A simple [Fragment] subclass.
 *
 */
open class BaseFragment : androidx.fragment.app.Fragment(), AuthView {


    fun getAppComponent() = (requireContext().applicationContext as App).appComponent


    override fun onError(t: Throwable) {
        if (t is ExpiredException) {
            EventBus.getDefault().post(LogoutEvent())
            TokenManager.clearToken()
            onAuthExpired()
        } else {
            t.message?.apply { Toaster.message(this) }
        }
    }

    override fun onAuthExpired() {
        (requireActivity() as BaseActivity).onAuthExpired()
    }


    private var disposableCollection: ArrayList<Disposable> = ArrayList()

    fun addToDiposable(disposable: Disposable?) {
        if (disposable != null && disposable.isDisposed.not())
            disposableCollection.add(disposable)
    }

    override fun onDestroy() {
        super.onDestroy()
        for (disposable in disposableCollection) {
            if (disposable.isDisposed.not())
                disposable.dispose()
        }
    }


    fun webViewHeader(): Map<String, String> {
        return mapOf(
                Pair("appdevice", "android")
                , Pair("plat", ChannelUtil.getChannel(App.instance))
                , Pair("apptoken", TokenManager.webviewHeaderToken())
                , Pair("appversion", BuildConfig.VERSION_CODE.toString())
                , Pair("Referer", "http://www.shandw.com")
                , Pair("mtype", "xiangguo")


        )
    }

}
